<script setup lang="ts">
import { ref } from 'vue'
import { userListService, addUserService, updateUserService, deleteUserService } from "@/api/user"
import {uploadService} from '@/api/upload'
import { roleListService } from "@/api/role"
import { ElMessage, ElMessageBox } from 'element-plus'
import {
    Edit,
    Delete,
    UploadFilled
} from '@element-plus/icons-vue'

const user = ref([
    {
        "id": 1,
        "avatar": "",
        "account": "20000101",
        "name": "zhangsan",
        "roleId": 1,
    }
])
//条件搜索模型
const name = ref('');
//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(10)//每页条数

const userList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
        name: name.value ? name.value : null,
    }
    let result = await userListService(params)

    //渲染视图
    total.value = result.data.total;
    user.value = result.data.records;
}
//调用函数查询
userList();
//当每页条数发生了变化，调用此函数
const handleSizeChange = (size: number) => {
    pageSize.value = size
    userList();
}
//当前页码发生变化，调用此函数
const handleCurrentChange = (num: number) => {
    page.value = num
    userList();
}

//用户角色数据模型
const roles = ref({
    "id": 1,
    "roleName": "管理员",
}) as any;
//用户角色数据回写
const roleList = async () => {
    let params = {
        page: page.value,
        pageSize: pageSize.value,
    }
    let result = await roleListService(params);
    roles.value = result.data.records
}
roleList();
//添加、修改会员表单模型
const userForm = ref({
    id: 1,
    name: '',
    roleId: 1,
    avatar: '',
})
//后台调用上传文件
const upload =async (param: { file: string | Blob }) => {
    let formData = new FormData();
    formData.append("file",param.file)
    let result = await uploadService(formData);
    userForm.value.avatar = result.data
}

//添加、修改会员的表单校验模型
const Rules = ref({
    name: [
        { required: true, message: '请输入用户账号', trigger: 'blur' }
    ],
    roleId: [
        { required: true, message: '请选择', trigger: 'blur' }
    ]
})
//默认不显示抽屉
const visibleDrawer = ref(false)
//为抽屉添加响应数据
const addUserRef = ref()
//后台调用添加用户接口
const onAdd = async () => {
    //点击添加按钮后再进行二次校验
    await addUserRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await addUserService(userForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '添加成功')
    //让抽屉消失
    visibleDrawer.value = false
    //刷新列表
    userList();
}
//刷新抽屉表单
const clearUserForm = () => {
    userForm.value = {
        id: 1,
        name: '',
        avatar: '',
        roleId: 1,
    }
}
//取消添加
const cancelDrawer = () => {
    visibleDrawer.value = false
}

//默认不显示对话框
const visibleDialog = ref(false)
//展示编辑对话框弹窗
const showDialog = (row: { name: string; avatar: string; roleId: number; id: any }) => {
    clearUserForm()
    visibleDialog.value = true
    //给编辑框回写原先信息
    userForm.value.name = row.name
    userForm.value.avatar = row.avatar
    userForm.value.roleId = row.roleId
    //扩展模型添加id
    userForm.value.id = row.id
}
//为对话框添加响应数据
const updateUserRef = ref()
//后台调用修改会员接口
const onUpdate = async () => {
    //点击修改后再进行二次校验
    await updateUserRef.value?.validate().catch((err: any) => { ElMessage.error("校验失败"); return Promise.reject(err) })
    let result = await updateUserService(userForm.value) as any;
    ElMessage.success(result.msg ? result.msg : '修改成功')
    //让对话框消失
    visibleDialog.value = false
    //刷新列表
    userList();
}

//取消修改
const cancelDialog = () => {
    visibleDialog.value = false
}

const deleteMember = (row: { id: any }) => {
    ElMessageBox.confirm(
        '确定要删除吗？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let result = await deleteUserService(row.id) as any;
            ElMessage({
                type: 'success',
                message: result.msg ? result.msg : '删除成功',
            })
            userList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>用户管理</span>
                <div class="extra">
                    <el-button type="primary" @click="visibleDrawer = true; clearUserForm()">添加用户</el-button>
                </div>
            </div>
        </template>
        <!-- 搜索表单 -->
        <el-form inline>
            <el-form-item prefix-icon="name" label="用户姓名：">
                <el-input v-model="name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="userList()">搜索</el-button>
                <el-button @click="name = ''">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 会员列表 -->
        <el-table :data="user" style="width: 100%">
            <el-table-column label="序号" width="100">
                <template v-slot="scope">
                    <!-- 序号实现自动增加且连续 -->
                    {{ (page - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="头像" prop="avatar" width="120">
                <template #default="scope">
                    <el-image v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]" 
                    style="width: 50px; height: 50px;border-radius: 5px">
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column label="用户账号" prop="account" width="200"></el-table-column>
            <el-table-column label="姓名" prop="name" width="200"></el-table-column>
            <el-table-column label="用户角色" prop="roleId" show-overflow-tooltip width="120">
                <!-- 将渲染的1，2转换为管理员，普通用户 -->
                <template v-slot="scope">{{ scope.row.roleId === 1 ? '管理员' : '普通用户' }}</template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="{ row }">
                    <el-button :icon="Edit"  plain type="primary" @click="showDialog(row)">编辑</el-button>
                    <el-button :icon="Delete"  plain type="danger" @click="deleteMember(row)">删除</el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
            layout="sizes,prev, pager,next,jumper,total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :total="total">
        </el-pagination>

        <!-- 抽屉中嵌套添加表单 -->
        <el-drawer v-model="visibleDrawer" title="添加用户" direction="rtl" destroy-on-close>
            <div>
                <el-form ref="addMemberRef" :model="userForm" :rules="Rules">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="userForm.name" autocomplete="off" />
                    </el-form-item>
                    <!--:http-request="upload" 不使用action 自己处理axios请求  -->
                    <el-form-item label="头像" prop="avatar">
                        <el-upload class="upload-demo" drag
                            :http-request="upload"
                            multiple
                            list-type="picture">
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                Drop file here or <em>click to upload</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    jpg/png files with a size less than 500kb
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="用户角色：" prop="roleId">
                        <el-select placeholder="请选择" v-model="userForm.roleId">
                            <el-option v-for="r in roles" :key="r.id" :label="r.roleName" :value="r.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDrawer(); clearUserForm()">取消</el-button>
                    <el-button type="primary" @click="onAdd">
                        添加
                    </el-button>
                </div>
            </div>
        </el-drawer>

        <!-- 对话框嵌套编辑表单 -->
        <el-dialog v-model="visibleDialog" title="修改用户" destroy-on-close>
            <div>
                <el-form ref="updateUserRef" :model="userForm" :rules="Rules">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="userForm.name" autocomplete="off" />
                    </el-form-item>
                    <!--:http-request="upload" 不使用action 自己处理axios请求  -->
                    <el-form-item label="头像" prop="avatar">
                        <el-upload class="upload-demo" drag
                            :http-request="upload"
                            multiple
                            list-type="picture">
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                Drop file here or <em>click to upload</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip">
                                    jpg/png files with a size less than 500kb
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="用户角色：" prop="roleId">
                        <el-select placeholder="请选择" v-model="userForm.roleId">
                            <el-option v-for="r in roles" :key="r.id" :label="r.roleName" :value="r.id">
                            </el-option>
                        </el-select>
                    </el-form-item>

                </el-form>
                <!-- 按钮设置 -->
                <div>
                    <el-button @click="cancelDialog(); clearUserForm()">取消</el-button>
                    <el-button type="primary" @click="onUpdate">
                        修改
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>